package com.alibam.core.wechat.token.server;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.alibam.core.wechat.common.Config;
import com.alibam.core.wechat.common.JedisUtil;
import com.alibam.core.wechat.token.AccessToken;
import com.alibam.core.wechat.token.Token;
import com.alibam.core.wechat.util.HttpUtils;

public class AccessTokenRedisServer extends CustomerServer {
	
	Logger logger = Logger.getLogger(AccessTokenRedisServer.class);

	public static final String WECHAT_ACCESS_TOKEN = "accessToken:wechat:%s";

	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

	@Override
	protected String find() {
		if (JedisUtil.get(wxAccessToken()) == null) {
			logger.info("==============未找到wechatAccessToken，初始化一个==============");
			return refresh();
		} else {
			String at = JedisUtil.get(wxAccessToken());
			logger.info("==============accessToken from redis==============");
			return at;
		}
	}

	@Override
	public boolean save(Token arg0) {
		JedisUtil.set(wxAccessToken(), arg0.getToken());
		return true;
	}

	public String refresh() {
		String appid = Config.instance().getAppid();
		String appsecret = Config.instance().getAppSecret();
		String url = ACCESS_TOKEN_URL + "&appid=" + appid + "&secret="
				+ appsecret;
		String result = HttpUtils.get(url);
		Token token = parseData(result);
		save(token);
		return token.getToken();
	}

	/**
	 * 解析token数据
	 * 
	 * @param data
	 * @return
	 */
	private Token parseData(String data) {
		JSONObject jsonObject = JSONObject.parseObject(data);
		String tokenName = "access_token";
		String expiresInName = "expires_in";
		AccessToken accessToken = new AccessToken();
		try {
			String token = jsonObject.get(tokenName).toString();
			if (StringUtils.isBlank(token)) {
				return null;
			}
			accessToken.setToken(token);
			String expiresIn = jsonObject.get(expiresInName).toString();
			if (StringUtils.isBlank(expiresIn)) {
				return null;
			} else {
				long expires = Long.valueOf(expiresIn);
				accessToken.setExpires(expires);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return accessToken;
	}

	private String wxAccessToken() {
		return String.format(WECHAT_ACCESS_TOKEN, Config.instance().getAppid());
	}
	
}
